using Aurora.TaskScheduler.Abstractions;
using Aurora.TaskScheduler.Abstractions.BaseModel;
using Aurora.TaskScheduler.Abstractions.Message;
using Aurora.TaskScheduler.Abstractions.SchedulerAttributes;
using Aurora.TaskScheduler.Abstractions.Storage;
using Microsoft.Extensions.Options;
using Quartz;

namespace Aurora.TaskScheduler.Extension.SchedulerImpl;

/// <summary>
/// 任务删除的处理器
/// </summary>
[DisallowConcurrentExecution]
[Cron("0 0 0 * * ?", "每天0点执行一次",description: "TaskJobScheduler自带方法,此方法用于删除过期的执行日志")]
public class TaskRemoveHandler : ITaskJob<string>
{
    private readonly TaskSchedulerOptions _options;

    private readonly IDataStorage _dataStorage;

    public TaskRemoveHandler(IOptions<TaskSchedulerOptions> options, IDataStorage dataStorage)
    {
        _dataStorage = dataStorage;
        _options = options.Value;
    }


    public async Task Remove(List<AppTaskLog> logs)
    {
        var ids = logs.Select(x => x.Id).ToList();
        await _dataStorage.RemoveLogRange(ids);
    }


    public async Task<JobResult> ExecuteAsync(string parameter)
    {
        // 先获取周期时长
        int page = 1;
        int size = 1000;
        var expireTime = DateTime.Now.AddDays(-1 * _options.RetentionTime);
        while (true)
        {
            var data = await _dataStorage.GetExpireLog(expireTime, page, size);
            if (data.list?.Count > 0)
            {
                // 开始删除数据
                await Remove(data.list);
                if (data.list.Count < size)
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }

        return new JobResult()
        {
            Success = true,
            Message = "定时删除任务执行日志执行成功了"
        };
    }
}